package com.lanchetech.user.service.impl;


import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.bean.request.PageReq;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.bean.vo.UserRoleVO;
import com.lanchetech.common.enums.MsgUserRoleEnum;
import com.lanchetech.common.enums.ResultCode;
import com.lanchetech.common.enums.ToggleEnum;
import com.lanchetech.common.enums.UserRoleEnum;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.service.DaoService;
import com.lanchetech.service.InviteCodeService;
import com.lanchetech.user.service.StaffService;
import org.hashids.Hashids;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class StaffServiceImpl implements StaffService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    ShopMapper shopMapper;

    @Autowired
    DaoService daoService;

    @Autowired
    InviteCodeService inviteCodeService;

    @Autowired
    CustomerRemarkMapper customerRemarkMapper;

    @Autowired
    CustomerAppointmentSettingMapper customerAppointmentSettingMapper;

    @Autowired
    MsgUserMapper msgUserMapper;

    @Autowired
    BossMapper bossMapper;

    @Value("${customer.hashid.couponsalt}")
    private String salt;

    private Long getUserShopId(User user) {
        return user.getShopId();
    }

    @Override
    public BaseResp addClerk(String hashId) {
        Hashids hashids = new Hashids(salt, 32);
        long[] result = hashids.decode(hashId);
        if (result == null || result.length != 2) {
            return new BaseResp(ResultCode.FAIL);
        }
        Long clerkId = result[0];
        Long time = result[1];
        if (time + 5 * 60 * 1000 < System.currentTimeMillis()) {
            return new BaseResp(ResultCode.STAFF_QRCODE_EXPIRE);
        }

        User clerk = userMapper.selectByPrimaryKey(clerkId);
        if (clerk == null) {
            return new BaseResp(ResultCode.USER_NOT_EXISTS);
        }
        UserRole exists = userRoleMapper.findOneByUserIdAndRoleId(clerkId, UserRoleEnum.ROLE_CLERK.getId());
        if (exists != null) {
            return new BaseResp(ResultCode.IS_CLERK);
        }

        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        Shop shop = shopMapper.findOneByUserId(user.getId());



        if (shop == null ) {
            Boss boss = bossMapper.findOneByShopIdAndUserId(user.getShopId(), user.getId());
            if(boss == null){
                return new BaseResp(ResultCode.FAIL);
            }else {
                shop = shopMapper.selectByPrimaryKey(user.getShopId());
            }
        }

        userMapper.updateShopIdById(shop.getId(), clerk.getId());

        userRoleMapper.insert(UserRole.builder()
                .userId(clerk.getId())
                .roleId(UserRoleEnum.ROLE_CLERK.getId())
                .relateId(shop.getId())
                .name(shop.getShopName())
                .createdAt(new Date())
                .build());
        return new BaseResp();
    }

    @Override
    public BaseResp removeUserRole(Long id) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Shop shop = shopMapper.findOneByUserId(user.getId());
        UserRole target = userRoleMapper.selectByPrimaryKey(id);
        if (shop.getId().equals(target.getRelateId())) {
            userRoleMapper.deleteByPrimaryKey(id);

            // 判断用户是否还有店长、老板角色，有则不删除shopId
            List<UserRole> userRoles = userRoleMapper.findAllByUserId(user.getId());
            boolean hasRole = false;
            for (UserRole item : userRoles) {
                if (UserRoleEnum.ROLE_SHOP.getId().equals(item.getRoleId()) || UserRoleEnum.ROLE_CLERK.getId().equals(item.getRoleId())) {
                    hasRole = true;
                }
            }

            if (!hasRole) {
                userMapper.updateShopIdById(null, target.getUserId());
            }

        } else {
            return new BaseResp(ResultCode.FAIL);
        }
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<UserRoleVO>> getShopUserRolePage(PageReq req) {
        if (!StringUtils.isEmpty(req.getNickname())) {
            User res = userMapper.findOneByNicknameLike(req.getNickname());
            if (res == null) {
                req.setUserId(0L);
            } else {
                req.setUserId(res.getId());
            }
        }
        if (!StringUtils.isEmpty(req.getPhone())) {
            User res = userMapper.findOneByUsername(req.getPhone());
            if (res == null) {
                req.setUserId(0L);
            } else {
                req.setUserId(res.getId());
            }
        }
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Shop shop = shopMapper.selectByPrimaryKey(user.getShopId());


        if(shop == null){
            ResultData resultData = new ResultData();
            resultData.setResultCode(ResultCode.FAIL);
            return resultData;
        }

        req.setRoleId(UserRoleEnum.ROLE_CLERK.getId());
        req.setRelateId(shop.getId());

        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<UserRole> list = userRoleMapper.findAllPage(req);
        List<UserRoleVO> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(UserRole::getUserId).collect(Collectors.toList()));

            List<MsgUser> msgUsers = msgUserMapper.findAllByTenantIdAndRole(shop.getId(), MsgUserRoleEnum.USER.getRole());

            Map<Long, Boolean> msgUserMap = new HashMap<>();

            msgUsers.stream().forEach(item -> msgUserMap.put(item.getRelateId(), true));

            list.stream().forEach(item -> {
                UserRoleVO vo = new UserRoleVO();
                BeanUtils.copyProperties(item, vo);
                vo.setAvatar(userMap.get(item.getUserId()).getAvatar());
                vo.setNickname(userMap.get(item.getUserId()).getNickname());
                vo.setPhone(userMap.get(item.getUserId()).getUsername());
                vo.setIsCustomService(msgUserMap.containsKey(item.getUserId()));
                result.add(vo);
            });
        }
        return PageHelpUtil.buildPage(result, page);
    }

    @Override
    public BaseResp toggleCustomService(Long userRoleId, Byte status) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        UserRole userRole = userRoleMapper.selectByPrimaryKey(userRoleId);

        if (userRole.getRelateId().equals(user.getShopId())) {
            if (ToggleEnum.ON.getStatus().equals(status)) {
                msgUserMapper.updateTenantIdByRelateIdAndRole(userRole.getRelateId(), userRole.getUserId(), MsgUserRoleEnum.USER.getRole());
            } else {
                msgUserMapper.updateTenantIdByRelateIdAndRole(null, userRole.getUserId(), MsgUserRoleEnum.USER.getRole());
            }
        }
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<CustomerRemark>> getCustomerRemarkPage(PageReq req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        req.setShopId(getUserShopId(user));
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<CustomerRemark> list = customerRemarkMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp editCustomerRemark(CustomerRemark customerRemark) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (customerRemark.getId() == null) {
            //添加
            customerRemark.setUserId(user.getId());
            customerRemark.setShopId(getUserShopId(user));
            customerRemark.setCreatedAt(new Date());
            customerRemark.setUpdatedAt(new Date());
            customerRemarkMapper.insert(customerRemark);
        } else {
            //修改
            if (getUserShopId(user).equals(customerRemarkMapper.selectByPrimaryKey(customerRemark.getId()).getShopId())) {
                customerRemark.setUpdatedAt(new Date());
                customerRemarkMapper.updateCustomerRemarkByPrimaryKeySelective(customerRemark);
            } else {
                return new BaseResp(ResultCode.FAIL);
            }

        }
        return new BaseResp();
    }

    @Override
    public BaseResp deleteCustomerRemark(Long id) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (customerRemarkMapper.selectByPrimaryKey(id).getShopId().equals(getUserShopId(user))) {
            CustomerRemark customerRemark = customerRemarkMapper.selectByPrimaryKey(id);
            if (customerRemark != null) {
                customerRemarkMapper.deleteByPrimaryKey(id);
            }
        } else {
            return new BaseResp(ResultCode.FAIL);
        }

        return new BaseResp();
    }

    @Override
    public ResultData<CustomerRemark> getCustomerRemarkDetail(Long id) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        CustomerRemark customerRemark = customerRemarkMapper.selectByPrimaryKey(id);
        if (customerRemark.getShopId().equals(getUserShopId(user))) {
            return new ResultData<>(customerRemark);
        }
        return new ResultData<>();
    }

    @Override
    public BaseResp editCustomerAppointmentSetting(CustomerAppointmentSetting customerAppointmentSetting) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (customerAppointmentSetting.getId() == null) {
            //添加
            customerAppointmentSetting.setShopId(getUserShopId(user));
            customerAppointmentSetting.setCreatedAt(new Date());
            customerAppointmentSetting.setUpdatedAt(new Date());
            customerAppointmentSettingMapper.insert(customerAppointmentSetting);
        } else {
            //编辑
            if (customerAppointmentSettingMapper.selectByPrimaryKey(customerAppointmentSetting.getId()).getShopId().equals(getUserShopId(user))) {
                customerAppointmentSetting.setUpdatedAt(new Date());
                customerAppointmentSettingMapper.updateCustomerAppointmentSettingByPrimaryKeySelective(customerAppointmentSetting);

            }
        }
        return new BaseResp();
    }

    @Override
    public ResultData<List<CustomerAppointmentSetting>> getCustomerAppointmentSetting(Long shopId) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (shopId.equals(getUserShopId(user))) {
            List<CustomerAppointmentSetting> list = customerAppointmentSettingMapper.selectAllByShopId(shopId);
            return new ResultData<>(list);

        }
        return new ResultData<>();
    }
}